package com.weimob.mcloud.wechatwork.customer.mq.handler.externaluser;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue;
import com.google.common.collect.Lists;
import com.weimob.mcloud.wechatwork.common.utils.CollUtils;
import com.weimob.mcloud.wechatwork.common.utils.JsonUtil;
import com.weimob.mcloud.wechatwork.core.adapter.enums.cdp.CDPMarkTypeEnum;
import com.weimob.mcloud.wechatwork.core.adapter.enums.cdp.CdpMarkMessageEventEnum;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.bos.request.ProductInstanceRequestDTO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.bos.request.QueryBosRequestDTO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.bos.response.MerchantDTO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.bos.response.ProductInstanceDTO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.cdp.request.customer.CDPUserMarkDTO;
import com.weimob.mcloud.wechatwork.core.adapter.service.BosAdapterService;
import com.weimob.mcloud.wechatwork.core.adapter.service.cdp.CdpUserAdapterService;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphereVid;
import com.weimob.mcloud.wechatwork.core.entity.relation.CustomerEmployeeRelation;
import com.weimob.mcloud.wechatwork.core.entity.relation.customer.Customer;
import com.weimob.mcloud.wechatwork.core.enums.customer.CustomerStatusEnum;
import com.weimob.mcloud.wechatwork.core.enums.customer.ExternalUserTypeEnum;
import com.weimob.mcloud.wechatwork.core.enums.customer.SubAddWayEnum;
import com.weimob.mcloud.wechatwork.core.service.privatesphere.PrivateSphereService;
import com.weimob.mcloud.wechatwork.core.service.statistic.StatisticsService;
import com.weimob.mcloud.wechatwork.core.service.statistic.request.StatisticsRequestInfo;
import com.weimob.mcloud.wechatwork.customer.constant.RedisLockConstant;
import com.weimob.mcloud.wechatwork.customer.convertor.customer.RelationConvert;
import com.weimob.mcloud.wechatwork.customer.domain.*;
import com.weimob.mcloud.wechatwork.customer.domain.artemis.CustomerChangeEventMsg;
import com.weimob.mcloud.wechatwork.customer.domain.artemis.CustomerSearchInitEventMsg;
import com.weimob.mcloud.wechatwork.customer.domain.artemis.CustomerSearchInitEventMsg.CorpWxUserInfoListBean;
import com.weimob.mcloud.wechatwork.customer.mq.dto.AddExternalUserSecondDTO;
import com.weimob.mcloud.wechatwork.customer.mq.handler.externaluser.retry.AddExternalUserRetry;
import com.weimob.mcloud.wechatwork.customer.mq.model.UserExternalUserDomain;
import com.weimob.mcloud.wechatwork.customer.mq.model.UserExternalUserStatisticDomain;
import com.weimob.mcloud.wechatwork.customer.redis.RedisService;
import com.weimob.mcloud.wechatwork.customer.service.impl.ArtemisService;
import com.weimob.mcloud.wechatwork.customer.service.user.enums.CDPFlowStatusEnum;
import com.weimob.mcloud.wechatwork.customer.service.user.enums.YesOrNoEnum;
import com.weimob.mcloud.wechatwork.customer.third.core.CustomerServiceProxy;
import com.weimob.mcloud.wechatwork.customer.third.customer.CustomerThird;
import com.weimob.saas.open.producer.interfaces.dto.OpenMessageDTO;
import com.weimob.saas.open.producer.interfaces.export.OpenMessageDubboService;
import com.weimob.soa.common.response.SoaResponse;
import com.weimob.soa.common.utils.SoaUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Create Time: 2021年01月18日 16:11
 *
 * @author maosheng.li
 **/
@Slf4j
@Service
public class AddCorpExternaluserSecondHandler {


    @Autowired
    private CustomerServiceProxy customerServiceProxy;

    @Reference
    private PrivateSphereService privateSphereService;

    @Autowired
    private ArtemisService artemisService;

    @Autowired
    @Qualifier("statisticThreadPool")
    private ThreadPoolTaskExecutor statisticThreadPool;

    @Autowired
    private RedisService redisService;

    @Reference
    private CdpUserAdapterService cdpUserAdapterService;

    @Reference
    private BosAdapterService bosAdapterService;

    @Reference
    private StatisticsService statisticsService;

    @Reference
    private OpenMessageDubboService openMessageDubboService;

    @Autowired
    private CustomerThird customerThird;

    @Autowired
    AddExternalUserRetry addExternalUserRetry;

    /**
     * 企微助手产品id
     */
    @Value("${aewc.productId:203}")
    private Long aewcProductId;


    /**
     * 消息去重
     */
    @Value("${customerSearchFlag.distinct.interval:120}")
    private Long customerSearchInterval;


    /**
     * widRetryFlag重试标识
     */
    @ApolloJsonValue("${wid.retry.flag.corpid:[]}")
    private List<String> widRetryCorpIds;


    public Boolean handleCorpExternalUser(AddExternalUserSecondDTO externalUserSecondDTO) {
        //当前要处理的员工和客户关联关系
        ExternalUserChangeInfo externalUserChangeInfo = externalUserSecondDTO.getExternalUserChangeInfo();
        String corpId = externalUserChangeInfo.getToUserName();
        Long bosId = externalUserSecondDTO.getBosId();
        String externalUserId = externalUserChangeInfo.getExternalUserID();
        log.info("开始企业微信外部联系人二次分发消息处理, externalUserId:{},bosId:{}", externalUserId, bosId);
        //1、校验私域信息
        PrivateSphere privateSphereRequest = new PrivateSphere();
        privateSphereRequest.setCorpId(corpId);
        privateSphereRequest.setBosId(bosId);
        privateSphereRequest.setProductId(aewcProductId);
        SoaResponse<PrivateSphere, Void> fetchPrivateSphere = privateSphereService.fetch(privateSphereRequest);
        if (0L != Long.parseLong(fetchPrivateSphere.getReturnCode()) || Objects.isNull(fetchPrivateSphere.getResponseVo())) {
            //2.1 企微私域不存在打印失败日志
            log.warn("二次分发查询私域信息失败,corpId:{},productId:{}", corpId, aewcProductId);
            return false;
        }
        PrivateSphere privateSphere = fetchPrivateSphere.getResponseVo();

        //2、校验本息客户信息
        Customer customer = customerServiceProxy.fetchCustomer(externalUserSecondDTO.getCustomerId(), null, privateSphere, ExternalUserTypeEnum.ALL);
        if (customer == null) {
            //1.1 理论客户信息必定存在（第一阶段已经落了数据） 如果查询不到 打印报错日志
            log.error("二次分发查询客户信息失败:{}", JSON.toJSONString(externalUserSecondDTO));
            return false;
        }
        //是否新客
        Boolean newUserFlag = externalUserSecondDTO.getNewUserFlag();
        CustomerEmployeeRelation currentRelation = externalUserSecondDTO.getCurrentRelation();
        List<CustomerEmployeeRelation> hisRelationList = externalUserSecondDTO.getHisRelationList();

        String userId = null;
        //历史同步，腾讯返回的消息是一个客户一个消息,实时相当于一个关系一个消息
        if (currentRelation.getEmployee() != null) {
            userId = currentRelation.getEmployee().getTxUserId();
        }
        //历史同步场景没有userId
        if (StringUtils.isNotEmpty(externalUserChangeInfo.getUserID())) {
            userId = externalUserChangeInfo.getUserID();
        } else {
            externalUserChangeInfo.setUserID(userId);
        }

        //3、数据统计需要依赖历史客户员工关系数据
        String lockKey = String.format(RedisLockConstant.AddCorpExternaluser, bosId, corpId, externalUserId, userId);
        boolean dumpFlag = redisService.setNXNew(lockKey, "1", 5, TimeUnit.SECONDS);
        if (dumpFlag) {
            handlStatistics(externalUserChangeInfo, customer, currentRelation,
                    newUserFlag, Lists.newArrayList(privateSphere), hisRelationList);
        }

        // 查询主客户wid
        Long superWid = customerThird.getSuperWid(privateSphere.getBosId(), externalUserId, privateSphere.getCorpId());

        //4、发送二次消息给到业务方使用
        ArtemisBaseInfo<UserExternalUserDomain> artemisBaseInfo = new ArtemisBaseInfo<>();
        artemisBaseInfo.setTopic(ArtemisConstant.Topic.WECHATWORK_USER_CUSTOMER_MSG);
        artemisBaseInfo.setProducer(ArtemisConstant.USER);
        UserExternalUserDomain userExternalUserDomain = new UserExternalUserDomain();
        userExternalUserDomain.setBosId(privateSphere.getBosId());
        userExternalUserDomain.setProductId(privateSphere.getProductId());
        userExternalUserDomain.setProductInstanceId(privateSphere.getProductInstanceId());
        userExternalUserDomain.setUserStateChangeFlag(externalUserSecondDTO.getUserStateChangeFlag());
        List<PrivateSphereVid> vids = privateSphere.getVids();
        if (CollectionUtils.isNotEmpty(vids) && vids.get(0).getVidType() != null) {
            userExternalUserDomain.setVid(vids.get(0).getVid());
            userExternalUserDomain.setVidType(vids.get(0).getVidType().getCode());
        }
        //4.1获取产品版本信息广告需要
        try {
            if (CollectionUtils.isNotEmpty(vids)) {
                ProductInstanceRequestDTO productInstanceRequestDTO = new ProductInstanceRequestDTO();
                productInstanceRequestDTO.setBosId(privateSphere.getBosId());
                productInstanceRequestDTO.setProductId(privateSphere.getProductId());
                productInstanceRequestDTO.setProductInstanceId(privateSphere.getProductInstanceId());
                productInstanceRequestDTO.setVid(vids.get(0).getVid());
                ProductInstanceDTO productInstanceDTO = SoaUtil.unpack(bosAdapterService.getProductInstanceInfo(productInstanceRequestDTO));
                if (productInstanceDTO != null) {
                    userExternalUserDomain.setProductVersionId(productInstanceDTO.getProductVersionId());
                }
            }
        } catch (Exception e) {
            log.error("获取产品版本信息失败,error", e);
        }

        if (currentRelation.getEmployee() != null) {
            userExternalUserDomain.setEmployeeId(currentRelation.getEmployee().getId());
        }
        userExternalUserDomain.setTxUserId(userId);
        userExternalUserDomain.setUnionid(customer.getUnionid());
        userExternalUserDomain.setWid(superWid);
        userExternalUserDomain.setCustomerId(customer.getId());
        userExternalUserDomain.setExternalUserId(customer.getExternalUserid());
        userExternalUserDomain.setState(externalUserChangeInfo.getState());
        if (StringUtils.isBlank(userExternalUserDomain.getState())) {
            //如果入参没有取 关系表中state
            userExternalUserDomain.setState(currentRelation.getState());
        }
        userExternalUserDomain.setNewUserFlag(externalUserSecondDTO.getNewUserFlag());
        userExternalUserDomain.setName(customer.getName());
        userExternalUserDomain.setWelcomeCode(externalUserChangeInfo.getWelcomeCode());
        userExternalUserDomain.setRemarkMobiles(externalUserSecondDTO.getRemarkMobiles());
        userExternalUserDomain.setCorpid(corpId);
        userExternalUserDomain.setAddWay(currentRelation.getAddWay().getCode());
        userExternalUserDomain.setExternalUserType(customer.getExternalUserType().getCode());
        userExternalUserDomain.setAddTime(currentRelation.getAddTime().getTime());
        userExternalUserDomain.setCustomWelcomeCode(StringUtils.isNotBlank(externalUserChangeInfo.getWelcomeCode()) ? externalUserChangeInfo.getWelcomeCode() : "no_welcomeCode");
        if (YesOrNoEnum.YES.getCode().equals(externalUserChangeInfo.getHistoryCustomerSync())) {
            userExternalUserDomain.setHistoryCustomerSync(YesOrNoEnum.YES.getCode());
        } else {
            userExternalUserDomain.setHistoryCustomerSync(YesOrNoEnum.NO.getCode());
        }
        artemisBaseInfo.setEvent(userExternalUserDomain);
        log.info("新中台消费外部联系人二次分发消息：request {}", JSON.toJSONString(artemisBaseInfo));
        Boolean sendBoolean = artemisService.sendToArtemis(artemisBaseInfo, bosId);
        log.info("新中台消费外部联系人二次分发消息 sendToArtemis.response {}", sendBoolean);

        //6、通知客户搜索，客户信息变更
        // 检索用渠道wid cdp打点用主wid
        List<String> phoneList = new ArrayList<>();
        if (StringUtils.isNotBlank(customer.getMobiles())) {
            phoneList.add(customer.getMobiles());
        } else {
            if (StringUtils.isNotBlank(customer.getPhone())) {
                phoneList.add(customer.getPhone());
            }
        }

        if (superWid == null || widRetryCorpIds.contains(corpId)) {
            //6.2 换取不到wid(可能是渠道消息延迟导致，需要重试）
            try {
                log.warn("外部联系人wid还未生成,externalUserId:{}", externalUserId);
                addExternalUserRetry.addExternalUserRetry(externalUserChangeInfo, privateSphere);
            } catch (Exception e) {
                log.error("外部联系人消息到延迟队列发送失败:", e);
            }
        } else {
            if (ExternalUserTypeEnum.WECHAT_CUSTOMER.equals(customer.getExternalUserType())) {
                //6.1 只针对客户身份是微信客户才给到客搜
                if (newUserFlag) {
                    //6.1.2 如果是新用户走客搜数据初始化流程
                    initCustomerSearchMsg(customer, superWid, Lists.newArrayList(currentRelation),
                            privateSphere, phoneList);
                } else {
                    boolean distinctFlag = redisService.setNXNew("updateCustomerSearchMsg:superWid:" + superWid, "", customerSearchInterval, TimeUnit.SECONDS);
                    if (distinctFlag) {
                        //6.1.3 如果是老用户走客搜数据变更流程
                        updateCustomerSearchMsg(superWid, privateSphere.getBosId(),
                                privateSphere.getProductInstanceId(), privateSphere.getProductId());
                    }
                }
            }

            try {
                QueryBosRequestDTO queryBosRequestDTO = new QueryBosRequestDTO();
                queryBosRequestDTO.setBosId(privateSphere.getBosId());
                MerchantDTO unpack = SoaUtil.unpack(bosAdapterService.queryWidByBosId(queryBosRequestDTO));

                OpenMessageDTO openMessageDTO = new OpenMessageDTO();
                openMessageDTO.setId(customer.getExternalUserid() + userId + currentRelation.getAddTime().getTime());
                openMessageDTO.setTopic(IpaasMsgConstant.Topic.IPAAS_CUSTOMER_ADD_MSG);
                openMessageDTO.setEvent(IpaasMsgConstant.Event.ADD);
                openMessageDTO.setBosId(privateSphere.getBosId());
                openMessageDTO.setWid(unpack.getWid());
                openMessageDTO.setOriginProductId(privateSphere.getProductId());
                openMessageDTO.setOriginProductInstanceId(privateSphere.getProductInstanceId());
                openMessageDTO.setMsgBody(JSON.toJSONString(userExternalUserDomain));

                log.info("新中台消费外部联系人二次分发ipass消息, request:{}", JSON.toJSONString(openMessageDTO));
                openMessageDubboService.sendOpenMessage(openMessageDTO);
            } catch (Exception e) {
                log.error("新中台消费外部联系人二次分发ipass消息失败:", e);
            }

            //7、打点客户属性信息到CDP
            CDPUserMarkDTO cdpUserMarkDTO = new CDPUserMarkDTO();
            cdpUserMarkDTO.setuKey(String.valueOf(superWid));
            cdpUserMarkDTO.setuKeyType("wid");
            cdpUserMarkDTO.setsChannelType(203);
            cdpUserMarkDTO.setsChannelId(privateSphere.getProductInstanceId());
            cdpUserMarkDTO.setBosId(privateSphere.getBosId());
            if (Objects.nonNull(externalUserChangeInfo.getCreateTime())) {
                cdpUserMarkDTO.setUpdateTime(String.valueOf(externalUserChangeInfo.getCreateTime() * 1000L));
            } else if (Objects.nonNull(currentRelation.getAddTime())) {
                cdpUserMarkDTO.setUpdateTime(String.valueOf(currentRelation.getAddTime().getTime()));
            }
            CdpDataJsonInfo cdpDataJsonInfo = new CdpDataJsonInfo();
            cdpDataJsonInfo.setProductInstanceId(privateSphere.getProductInstanceId());
            cdpDataJsonInfo.setWid(superWid);
            cdpDataJsonInfo.setCorpId(corpId);
            cdpDataJsonInfo.setExternalUserId(externalUserId);
            cdpDataJsonInfo.setWechatNickName(customer.getName());
            cdpDataJsonInfo.setGender(customer.getGender().getCode());
            cdpDataJsonInfo.setAddWay(currentRelation.getAddWay().getCode());
            cdpDataJsonInfo.setAddWayDesc(currentRelation.getAddWay().getDesc());
            cdpDataJsonInfo.setCorpFullName(customer.getCorpFullName());
            cdpDataJsonInfo.setAvatar(customer.getAvatar());
            cdpDataJsonInfo.setRemark(currentRelation.getRemark());
            cdpDataJsonInfo.setOrgUserId(currentRelation.getEmployee().getId());
            cdpDataJsonInfo.setOrgUserName(currentRelation.getEmployee().getName());
            cdpDataJsonInfo.setAddValue(externalUserChangeInfo.getState());
            cdpDataJsonInfo.setFlowStatus(CDPFlowStatusEnum.NOT_FLOW_STATUS.getCode());
            if (currentRelation.getStatus() != null) {
                cdpDataJsonInfo.setCustomerStatus(currentRelation.getStatus().getCode());
            }
            cdpDataJsonInfo.setAddValue(externalUserChangeInfo.getState());
            cdpUserMarkDTO.setDataJson(JSONObject.parseObject(JSON.toJSONString(cdpDataJsonInfo)));
            // 客户有效才发打点
            if (currentRelation.getStatus() != null && CustomerStatusEnum.DEFAULT.getCode().equals(currentRelation.getStatus().getCode())) {
                cdpUserMarkDTO.setCdpMarkTypeEnum(CDPMarkTypeEnum.CDP_USER_ATTRIBUTE);
                cdpUserMarkDTO.setCdpMarkMessageEventEnum(CdpMarkMessageEventEnum.CUSTOMER_ATTRIBUTE);

                log.info("新中台消费外部联系人CDP打点属性事件：request {}", JSON.toJSONString(cdpUserMarkDTO));
                cdpUserAdapterService.markCDPUserMsg(cdpUserMarkDTO);
            }

            //8、打点客户行为到CDP
            if (!(YesOrNoEnum.YES.getCode().equals(externalUserChangeInfo.getHistoryCustomerSync()))) {
                //只是实时客户才进行行为打点
                cdpUserMarkDTO.setCdpMarkTypeEnum(CDPMarkTypeEnum.CDP_USER_ACTION);
                cdpUserMarkDTO.setCdpMarkMessageEventEnum(CdpMarkMessageEventEnum.ADD_FRIEND);
                log.info("新中台消费外部联系人CDP打点行为事件：request {}", JSON.toJSONString(cdpUserMarkDTO));
                cdpUserAdapterService.markCDPUserMsg(cdpUserMarkDTO);
            }
        }

        return true;
    }


    /**
     * 客户变更消息
     *
     * @param bosId
     * @param piid
     * @param productId
     */
    public void updateCustomerSearchMsg(Long wid, Long bosId, Long piid, Long productId) {
        CustomerChangeEventMsg customerChangeEventMsg = new CustomerChangeEventMsg();
        customerChangeEventMsg.setBosId(bosId);
        customerChangeEventMsg.setSourceProductInstanceId(piid);
        customerChangeEventMsg.setSourceProductId(productId);
        customerChangeEventMsg.setWids(Lists.newArrayList(wid));
        ArtemisBaseInfo artemisBaseInfo = new ArtemisBaseInfo();
        artemisBaseInfo.setTopic(ArtemisConstant.Topic.CORE_EXTERNALUSER_CHANG_EVENT);
        artemisBaseInfo.setEvent(customerChangeEventMsg);
        artemisBaseInfo.setProducer(ArtemisConstant.USER);
        log.info("通知客搜客户变更, bosId:{}, wid:{}", bosId, wid);
        artemisService.sendToArtemis(artemisBaseInfo, bosId);
    }

    /**
     * 历史客户变更消息
     *
     * @param bosId
     * @param piid
     * @param productId
     */
    public void updateCustomerSearchHisMsg(Long wid, Long bosId, Long piid, Long productId) {
        CustomerChangeEventMsg customerChangeEventMsg = new CustomerChangeEventMsg();
        customerChangeEventMsg.setBosId(bosId);
        customerChangeEventMsg.setSourceProductInstanceId(piid);
        customerChangeEventMsg.setSourceProductId(productId);
        customerChangeEventMsg.setWids(Lists.newArrayList(wid));
        ArtemisBaseInfo artemisBaseInfo = new ArtemisBaseInfo();
        artemisBaseInfo.setTopic(ArtemisConstant.Topic.HIS_CORE_EXTERNALUSER_CHANG_EVENT);
        artemisBaseInfo.setEvent(customerChangeEventMsg);
        artemisBaseInfo.setProducer(ArtemisConstant.USER);
        log.info("历史数据变更通知客搜, bosId:{}, wid:{}", bosId, wid);
        artemisService.sendToArtemis(artemisBaseInfo, bosId);
    }

    /**
     * 初始化数据到用户搜索服务
     *
     * @param customer
     * @param wid
     * @param privateSphere
     */
    public void initCustomerSearchMsg(Customer customer, Long wid,
                                      List<CustomerEmployeeRelation> customerEmployeeRelationList, PrivateSphere privateSphere, List<String> phoneList) {
        //只有客户状态为有效的时候才进行初始化
        List<CustomerEmployeeRelation> relationList = customerEmployeeRelationList.stream().filter(item -> CustomerStatusEnum.DEFAULT.getCode().equals(item.getStatus().getCode())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(relationList)) {
            return;
        }
        CustomerSearchInitEventMsg customerSearchMsg = new CustomerSearchInitEventMsg();
        customerSearchMsg.setBosId(privateSphere.getBosId());
        customerSearchMsg.setSourceProductInstanceId(privateSphere.getProductInstanceId());
        customerSearchMsg.setSourceProductId(privateSphere.getProductId());
        customerSearchMsg.setWid(wid);
        customerSearchMsg.setNickname(customer.getName());
        customerSearchMsg.setGender(customer.getGender().getCode());
        customerSearchMsg.setAppId(customer.getCorpId());
        customerSearchMsg.setExternalUserId(customer.getExternalUserid());
        customerSearchMsg.setPhone(phoneList);
        //根据时间倒序展示 设置最新添加事件添加方式
        List<CustomerEmployeeRelation> sortedDataList = relationList.stream().sorted(Comparator.comparing(CustomerEmployeeRelation::getAddTime).reversed()).collect(Collectors.toList());
        customerSearchMsg.setCorpWxLastAddTime(sortedDataList.get(0).getAddTime());
        if (customer.getFirstAddTime() != null) {
            customerSearchMsg.setCorpWxFirstAddTime(customer.getFirstAddTime().getTime());
        }
        customerSearchMsg.setCorpWxUserNum(sortedDataList.size());
        customerSearchMsg.setCorpWxFriendNum(sortedDataList.size());
        //权限vidList
        customerSearchMsg.setAuthorizeVidList(RelationConvert.mergeVidList(relationList));

        List<CorpWxUserInfoListBean> corpWxUserInfoList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(relationList)) {
            for (CustomerEmployeeRelation customerEmployeeRelation : relationList) {
                CorpWxUserInfoListBean corpWxUserInfoListBean = new CorpWxUserInfoListBean();
                if (customerEmployeeRelation.getEmployee() != null) {
                    corpWxUserInfoListBean.setUserId(customerEmployeeRelation.getEmployee().getId());
                }
                corpWxUserInfoListBean.setAddTime(customerEmployeeRelation.getAddTime());
                corpWxUserInfoListBean.setFriended(1);
                if (customerEmployeeRelation.getAddWay() != null) {
                    corpWxUserInfoListBean.setAddWay(customerEmployeeRelation.getAddWay().getCode());
                }
                SubAddWayEnum subAddWay = customerEmployeeRelation.getSubAddWay();
                if (Objects.nonNull(subAddWay)) {
                    corpWxUserInfoListBean.setSubAddWay(Collections.singletonList(subAddWay.getCode()));
                }
                corpWxUserInfoList.add(corpWxUserInfoListBean);

            }
        }
        customerSearchMsg.setAuthorizationState(CustomerStatusEnum.DEFAULT.getCode());

        customerSearchMsg.setCorpWxUserInfoList(corpWxUserInfoList);
        ArtemisBaseInfo artemisBaseInfo = new ArtemisBaseInfo();
        artemisBaseInfo.setTopic(ArtemisConstant.Topic.CORE_EXTERNALUSER_INIT_EVENT);
        artemisBaseInfo.setEvent(customerSearchMsg);
        artemisBaseInfo.setProducer(ArtemisConstant.USER);
        log.info("初始化数据到用户搜索服务发消息, request:{}", JSON.toJSONString(artemisBaseInfo));
        artemisService.sendToArtemis(artemisBaseInfo, privateSphere.getBosId());
    }


    /**
     * 处理数据统计逻辑
     */
    private void handlStatistics(ExternalUserChangeInfo externalUserChageInfo,
                                 Customer customer, CustomerEmployeeRelation customerEmployeeRelation,
                                 Boolean newUserFlag, List<PrivateSphere> privateSphereResultList,
                                 List<CustomerEmployeeRelation> hisRelationList) {
        String corpId = externalUserChageInfo.getToUserName();
        log.info("handlStatistics start corpId:{},externalUserId:{},newFlag:{}", corpId, externalUserChageInfo.getExternalUserID(), newUserFlag);
        try {
            List<CustomerEmployeeRelation> oldRelations = new ArrayList<>();
            if (!newUserFlag) {
                oldRelations = hisRelationList;
            }
            List<CustomerEmployeeRelation> finalOldRelations = oldRelations;
            if (externalUserChageInfo.getHistoryCustomerSync() != null && externalUserChageInfo.getHistoryCustomerSync() == 1) {
                //同步逻辑
                statisticThreadPool.execute(() -> handleHistoryExternalUserStatistic(corpId, customer, customerEmployeeRelation,
                        finalOldRelations, privateSphereResultList));
            } else {
                String state = externalUserChageInfo.getState();
                statisticThreadPool.execute(() -> handleExternalUserStatistic(corpId, state, customer, customerEmployeeRelation,
                        finalOldRelations, privateSphereResultList));
            }
        } catch (Exception e) {
            log.error("handlStatistics error", e);
        }
    }

    private void handleExternalUserStatistic(String corpId, String state,
                                             Customer customer, CustomerEmployeeRelation currentEmployeeRelation,
                                             List<CustomerEmployeeRelation> historyEmployeeRelation, List<PrivateSphere> privateSphereResultList) {
        // 有unionid的人才进入数据统计
        if (customer == null) {
            return;
        }
        String externalUserId = customer.getExternalUserid();
        // 判断是否处理过了，可能是初始化数据,走这个方法，需要过滤
        if (CollectionUtils.isNotEmpty(historyEmployeeRelation)) {
            List<CustomerEmployeeRelation> corpUserExternaluserList = historyEmployeeRelation.stream().filter(e ->
                    e.getEmployee().getId().equals(currentEmployeeRelation.getEmployee().getId())
                            && e.getAddTime().equals(currentEmployeeRelation.getAddTime())
                            && e.getFriended()
            ).collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(corpUserExternaluserList)) {
                log.info("such externalUser has been handled, externalUser {}, addTime {}", externalUserId, currentEmployeeRelation.getAddTime());
                return;
            }
        }
        PrivateSphere privateSphere = new PrivateSphere();
        privateSphere.setCorpId(corpId);
        StatisticsRequestInfo statisticsRequestInfo = new StatisticsRequestInfo();
        List<String> privateSphereIds = CollUtils.map(privateSphereResultList, PrivateSphere::getPrivateSphereId);
        statisticsRequestInfo.setPrivateSphereIds(privateSphereIds);
//        statisticsRequestInfo.setCorpUserExternalusers(corpUserExternalusers);
        statisticsRequestInfo.setExternalUserId(externalUserId);
        statisticsRequestInfo.setState(state);
        statisticsRequestInfo.setAddWay(currentEmployeeRelation.getAddWay().getCode());
        statisticsRequestInfo.setUserid(currentEmployeeRelation.getEmployee().getTxUserId());
        statisticsRequestInfo.setCreatetime(currentEmployeeRelation.getAddTime().getTime() / 1000);
        statisticsRequestInfo.setPrivateSphere(privateSphere);
        //标志参数
        statisticsRequestInfo.setOldRelationExist(CollectionUtils.isEmpty(historyEmployeeRelation));
        List<CustomerEmployeeRelation> isDeletedExternalUsers = getIsDeletedExternalUser(historyEmployeeRelation);
        statisticsRequestInfo.setAllReleased(historyEmployeeRelation.size() == isDeletedExternalUsers.size());
        if (StringUtils.isNotEmpty(state)) {
            //判断添加方式中有无该活码
            Boolean flag = false;
            for (CustomerEmployeeRelation corpUserExternaluser : historyEmployeeRelation) {
                if (corpUserExternaluser.getState().equals(state)) {
                    flag = true;
                }
            }
            statisticsRequestInfo.setStateFlag(flag);
        }
        // TODO: 2021/11/16 这个userid的含义待确认
        List<CustomerEmployeeRelation> addWayUsers = historyEmployeeRelation.stream().filter(c -> c.getEmployee().getId().equals(currentEmployeeRelation.getEmployee().getId())).collect(Collectors.toList());
        statisticsRequestInfo.setAddWayFlag(CollectionUtils.isEmpty(addWayUsers));
        //有这个userid添加方式
        if (!statisticsRequestInfo.getAddWayFlag()) {
            statisticsRequestInfo.setLastRelation(addWayUsers.get(0));
        }

        log.info("handleExternalUserStatistic start,request:{}", JsonUtil.obj2Str(statisticsRequestInfo));
        sendToStatisticTopic(statisticsRequestInfo, 1);
    }

    /**
     * 取非好友关系
     */
    private List<CustomerEmployeeRelation> getIsDeletedExternalUser(List<CustomerEmployeeRelation> corpUserExternalusers) {
        List<CustomerEmployeeRelation> isDeletedExternalUsers = Lists.newArrayList();
        for (CustomerEmployeeRelation corpUserExternaluser : corpUserExternalusers) {
            if (corpUserExternaluser.getFriended().equals(Boolean.FALSE)) {
                isDeletedExternalUsers.add(corpUserExternaluser);
            }
        }
        return isDeletedExternalUsers;
    }

    private void handleHistoryExternalUserStatistic(String corpId, Customer customer,
                                                    CustomerEmployeeRelation customerEmployeeRelation, List<CustomerEmployeeRelation> corpUserExternalusers,
                                                    List<PrivateSphere> privateSphereResultList) {
        // TODO: 2021/11/16 白名单逻辑
        // 有unionid的人才进入数据统计
        if (customer == null) {
            return;
        }
        String externalUserId = customer.getExternalUserid();
        // 判断是否处理过了，可能是初始化数据,走这个方法，需要过滤
        if (CollectionUtils.isNotEmpty(corpUserExternalusers)) {
            List<CustomerEmployeeRelation> corpUserExternaluserList = corpUserExternalusers.stream().filter(e ->
                    e.getEmployee().getId().equals(customerEmployeeRelation.getEmployee().getId())
            ).collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(corpUserExternaluserList)) {
                log.info("such externalUser has been handled, externalUser {}, addTime {}",
                        externalUserId, customerEmployeeRelation.getAddTime());
                return;
            }
        }
        PrivateSphere privateSphere = new PrivateSphere();
        privateSphere.setCorpId(corpId);
        StatisticsRequestInfo statisticsRequestInfo = new StatisticsRequestInfo();
        List<String> privateSphereIds = CollUtils.map(privateSphereResultList, PrivateSphere::getPrivateSphereId);
        statisticsRequestInfo.setPrivateSphereIds(privateSphereIds);
        statisticsRequestInfo.setExternalUserId(externalUserId);
        statisticsRequestInfo.setState(customerEmployeeRelation.getState());
        statisticsRequestInfo.setAddWay(customerEmployeeRelation.getAddWay().getCode());
        statisticsRequestInfo.setCreatetime(customerEmployeeRelation.getAddTime().getTime() / 1000);
        statisticsRequestInfo.setPrivateSphere(privateSphere);
        log.info("handleHistoryExternalUserStatistic start,request:{}", JsonUtil.obj2Str(statisticsRequestInfo));

        sendToStatisticTopic(statisticsRequestInfo, 0);

    }

    private void sendToStatisticTopic(StatisticsRequestInfo statisticsRequestInfo, Integer type) {
        UserExternalUserStatisticDomain userExternalUserStatisticDomain = new UserExternalUserStatisticDomain();

        userExternalUserStatisticDomain.setAddWayFlag(statisticsRequestInfo.getAddWayFlag());
        userExternalUserStatisticDomain.setStateFlag(statisticsRequestInfo.getStateFlag());
        userExternalUserStatisticDomain.setAllReleased(statisticsRequestInfo.getAllReleased());
        userExternalUserStatisticDomain.setOldRelationExist(statisticsRequestInfo.getOldRelationExist());
        userExternalUserStatisticDomain.setStatisticDate(statisticsRequestInfo.getStatisticDate());
        userExternalUserStatisticDomain.setIfIsReleased(statisticsRequestInfo.getIfIsReleased());
        userExternalUserStatisticDomain.setUserid(statisticsRequestInfo.getUserid());
        userExternalUserStatisticDomain.setCreatetime(statisticsRequestInfo.getCreatetime());
        userExternalUserStatisticDomain.setAddWay(statisticsRequestInfo.getAddWay());
        userExternalUserStatisticDomain.setState(statisticsRequestInfo.getState());
        userExternalUserStatisticDomain.setExternalUserId(statisticsRequestInfo.getExternalUserId());
        userExternalUserStatisticDomain.setPrivateSphere(statisticsRequestInfo.getPrivateSphere());
        userExternalUserStatisticDomain.setPrivateSphereIds(statisticsRequestInfo.getPrivateSphereIds());
        userExternalUserStatisticDomain.setLastRelation(statisticsRequestInfo.getLastRelation());
        userExternalUserStatisticDomain.setType(type);
        ArtemisBaseInfo<UserExternalUserStatisticDomain> artemisBaseInfo = new ArtemisBaseInfo<>();
        artemisBaseInfo.setTopic(ArtemisConstant.Topic.WECHATWORK_USER_STATISTIC_MSG);
        artemisBaseInfo.setProducer(ArtemisConstant.USER);
        artemisBaseInfo.setEvent(userExternalUserStatisticDomain);
        log.info("新中台消费外部联系人统计分发消息：externalUserId: {},privateSphereId:{}", userExternalUserStatisticDomain.getExternalUserId(), JSON.toJSONString(userExternalUserStatisticDomain.getPrivateSphereIds()));
        Boolean sendBoolean = artemisService.sendToArtemis(artemisBaseInfo);
        log.info("新中台消费外部联系人统计分发消息 sendToArtemis.response {}", sendBoolean);
    }

}
